<template>
    <div style="margin-top: 5px">
        <create-sections
            title="甲方信息">
            <component
                v-if="isShow"
                ref="contractForm_partA"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :value="value"
                :action="action"
                form-modular='partA'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="乙方信息">
            <component
                v-if="isShow"
                ref="contractForm_partB"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :value="value"
                :action="action"
                form-modular='partB'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="付款节点及金额">
            <flexbox slot="header">
                <flexbox style="padding-left: 10px;color: #909399">
                    <span>（最多添加5个付款节点）</span>
                </flexbox>
            </flexbox>
            <flexbox justify="flex-end" style="padding: 0 10px">
                <span>总金额：{{finalMoney}}元</span>
                <el-button type="primary" size="mini" style="margin-left: 10px" @click="addPaymentItem" :disabled="checkList.paymentIsAll">
                    添加付款节点
                </el-button>
            </flexbox>
            <el-table
                :data="paymentList"
                :row-class-name="tableRowClassName"
                style="width: 100%;">
                <el-table-column
                    width="80"
                    prop="paymentNodeNumber"
                    label="序号">
                </el-table-column>
                <el-table-column
                    width="100"
                    prop="payName"
                    label="节点名称">
                </el-table-column>
                <el-table-column label="付款条件" width="260">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-autocomplete
                            style="width: 100%"
                            popper-class="input-popper"
                            :maxlength="10"
                            show-word-limit
                            v-model="scope.row.paymentCondition"
                            :fetch-suggestions="querySearch"
                            placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="付款周期（天）">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.paymentCycle"
                            type="number"
                            @mousewheel.native.prevent
                            @change="changePaymentCycle(scope.$index)"
                            placeholder="请输入"/>
                    </template>
                </el-table-column>
                <el-table-column label="付款百分比（%）">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.paymentPercentage"
                            type="number"
                            @mousewheel.native.prevent
                            @change="changePaymentPercentage(scope.$index)"
                            placeholder="请输入"/>
                    </template>
                </el-table-column>
                <el-table-column label="付款金额（元）">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.paymentAmount"
                            :max="100"
                            type="number"
                            @mousewheel.native.prevent
                            @change="changePaymentAmount(scope.$index)"
                            placeholder="请输入"/>
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                        <el-button type="danger" plain @click="paymentRemoveItem(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </create-sections>
        <create-sections
            title="开票节点及金额">
            <flexbox slot="header">
                <flexbox style="padding-left: 10px;color: #909399">
                    <span>（最多添加5个开票节点）</span>
                </flexbox>
            </flexbox>
            <flexbox justify="flex-end" style="padding: 0 10px">
                <span>总金额：{{finalMoney}}元</span>
                <el-button type="primary" size="mini" style="margin-left: 10px" @click="addTnvoiceItem" :disabled="!checkList.paymentIsAll || checkList.invoiceIsAll">
                    添加开票节点
                </el-button>
            </flexbox>
            <el-table
                :data="invoiceList"
                :row-class-name="tableRowClassName"
                style="width: 100%;">
                <el-table-column
                    width="80"
                    prop="invoiceNodeNumber"
                    label="序号">
                </el-table-column>
                <el-table-column label="填写收款节点">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-autocomplete
                            style="width: 100%"
                            popper-class="input-popper"
                            :maxlength="10"
                            show-word-limit
                            v-model="scope.row.paymentNodeNumber"
                            :fetch-suggestions="querySearchPayList"
                            placeholder="请输入" />
                        <!-- <el-select
                            v-model="scope.row.paymentNodeNumber"
                            placeholder="请选择" >
                            <el-option
                                v-for="(item, index) in paymentOptions"
                                :key="index"
                                :label="item.name"
                                :value="item.value"/>
                        </el-select> -->
                    </template>
                </el-table-column>
                <el-table-column label="开票周期">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        
                        <el-select
                            v-model="scope.row.invoiceCycle"
                            placeholder="请选择" >
                            <el-option
                                v-for="(item, index) in invoiceCycleOption"
                                :key="index"
                                :label="item.name"
                                :value="item.value"/>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="开票金额（元）">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.invoiceAmount"
                            type="number"
                            @mousewheel.native.prevent
                            @change="changeInvoiceAmount(scope.$index)"
                            placeholder="请输入"/>
                    </template>
                </el-table-column>
                <el-table-column label="开票税率（%）">
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.invoicePercentage"
                            type="number"
                            :disabled="true"
                            @mousewheel.native.prevent/>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                        <el-button type="danger" plain @click="invoiceRemoveItem(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </create-sections>
        <create-sections
            title="甲方开票信息">
            <component
                v-if="isShow"
                ref="contractForm_invoice"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :value="value"
                :action="action"
                form-modular='invoice'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="产品交付与验收">
            <component
                v-if="isShow"
                ref="contractForm_pdaa"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :options="paymentOptions"
                :value="value"
                :action="action"
                form-modular='pdaa'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="质量保证、保修及服务期限">
            <component
                v-if="isShow"
                ref="contractForm_qas"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :value="value"
                :action="action"
                form-modular='qas'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="一般条款">
            <component
                v-if="isShow"
                ref="contractForm_other"
                :is="'XhContractForm'"
                :form-data="formData"
                :form-rules="formRules"
                :value="value"
                :action="action"
                form-modular='other'
                @value-change="formValueChange" />
        </create-sections>
        <create-sections
            title="合同附件">
            <flexbox slot="header">
                <flexbox style="padding-left: 10px;color: #909399">
                    <span>（如有其它附件请上传，如：技术协议等）</span>
                </flexbox>
            </flexbox>
            <flexbox justify="flex-end" style="padding: 0 10px">
                <el-button type="primary" size="mini" style="margin-left: 10px" @click="addFiles">
                    添加附件
                </el-button>
            </flexbox>
            <el-table
                :data="annexList"
                :row-class-name="tableRowClassName"
                style="width: 100%;">
                <el-table-column
                    width="80"
                    label="序号">
                    <template slot-scope="scope">
                        <span>{{scope.$index + 1}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="附件名称">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.annexName"
                            type="text"
                            clearable
                            placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="选择文件（每个最多上传一个文件）">
                    <template
                        slot="header"
                        slot-scope="scope">
                        <div :title="scope.column.label">{{ scope.column.label }}<span style="color: red">*</span></div>
                    </template>
                    <template slot-scope="scope">
                        <component
                            :is="'XhFiles'"
                            :value="scope.row.files"
                            :file-limit="1"
                            :index="scope.$index"
                            @value-change="fileDataChange" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                        <el-button type="danger" plain @click="removeFile(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </create-sections>
        
    </div>
  
</template>

<script>
import CreateSections from '@/components/CreateSections'
import {
    XhContractForm,
    XhFiles
} from '@/components/CreateCom'
import {
  objDeepCopy,
  regexIsNumber,
  numberAdd, numberSub,numberMul,numberDiv,numberSaveFloat
} from '@/utils'
import {
  toolOptions
} from '@/utils/options'
export default {
    components: {
        XhContractForm,
        XhFiles,
        CreateSections
    },
    
    props: {
        value: {
            type: Object,
            default: () => {
                return {}
            }
        },
        action: {
            type: Object,
            default: () => {
                return {
                    type: 'save',
                    id: '',
                    data: {} // 编辑所需信息
                }
            }
        }
    },
    data(){
        return {
            partInvoice: {}, // 开票信息
            contractInfo: {}, // 合同其他相关信息，包含甲方信息，乙方信息，产品交付与验收，质量保证、保修及服务期限
            //付款节点及金额
            paymentList: [], 
            // 开票节点及金额
            invoiceList: [], 
             //合同附件
            annexList: [],
            formRules: {}, //字段校验规则
            isShow: false,
            // 自定义字段信息表单
            fieldList: {
                // 甲方信息
                partA: [
                    { fieldName: 'partACompanyName', name: '公司名称',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partACompanyAddress', name: '通讯地址',formType: 'textarea',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partACompanyContactName', name: '联系人姓名',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partACompanyPhone', name: '联系人电话',formType: 'text',value: '',defaultValue: '' ,isNull: 1},
                    { fieldName: 'partACompanyFax', name: '传真',formType: 'text',value: '',defaultValue: '' ,isNull: 0},
                    { fieldName: 'partACompanyEmail', name: '邮箱',formType: 'text',value: '',defaultValue: '' ,isNull: 0},
                ],
                // 乙方信息
                partB: [
                    { fieldName: 'partBCompanyName', name: '公司名称',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partBCompanyAddress', name: '通讯地址',formType: 'textarea',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partBCompanyContactName', name: '联系人姓名',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partBCompanyPhone', name: '联系人电话',formType: 'text',value: '',defaultValue: '' ,isNull: 1},
                    { fieldName: 'partBCompanyFax', name: '传真',formType: 'text',value: '',defaultValue: '' ,isNull: 0},
                    { fieldName: 'partBCompanyEmail', name: '邮箱',formType: 'text',value: '',defaultValue: '' ,isNull: 0},
                ],
                // 甲方开票信息
                invoice: [
                    { fieldName: 'partCompanyName', name: '公司名称',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partCompanyTaxNumber', name: '公司税号',formType: 'text',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partCompanyAddress', name: '注册地址',formType: 'textarea',value: '',defaultValue: '',isNull: 1},
                    { fieldName: 'partCompanyBank', name: '开户银行',formType: 'text',value: '',defaultValue: '' ,isNull: 1},
                    { fieldName: 'partCompanyBankAccount', name: '银行账号',formType: 'text',value: '',defaultValue: '' ,isNull: 1},
                    { fieldName: 'partCompanyPhone', name: '电话号码',formType: 'text',value: '',defaultValue: '' ,isNull: 1},
                ],
                // 产品交付与验收
                pdaa: [
                    { fieldName: 'hardwareDeliveryConditions', name: '发货条件',formType: 'autocomplete',value: '',setting: [],defaultValue: '',isNull: 1},
                    { fieldName: 'hardwareDeliveryCycle', name: '发货周期（天）',formType: 'number',value: '',defaultValue: 2,isNull: 1},
                    { fieldName: 'hardwareFreightBearer', name: '运费承担者',formType: 'select',value: '',setting: ['甲方','乙方'],defaultValue: '乙方',isNull: 1},
                    { fieldName: 'hardwareReceivingCycle', name: '收货周期（天）',formType: 'number',value: '',defaultValue: 2 ,isNull: 1},
                    { fieldName: 'hardwareWrittenNotificationPeriod', name: '书面通知周期（天）',formType: 'number',value: '',defaultValue: 2 ,isNull: 1},
                    { fieldName: 'hardwareConfirmationLeadTime', name: '交付周期（天）',formType: 'number',value: '',defaultValue: 2 ,isNull: 1},
                    { fieldName: 'softwareTrainingCycle', name: '软件培训周期（天）',formType: 'number',value: '',defaultValue: 2 ,isNull: 1},
                ],
                // 质量保证、保修及服务期限
                qas: [
                    { fieldName: 'warrantyPeriod', name: '保修期（月）',formType: 'number',value: '',defaultValue: 12,isNull: 1},
                    { fieldName: 'warrantyMethod', name: '保修方式',formType: 'text',value: '',defaultValue: '交换式',isNull: 1},
                    { fieldName: 'serviceTerm', name: '服务期限（月）',formType: 'number',value: '',defaultValue: 12,isNull: 1},
                    { fieldName: 'onSiteResponseCycle', name: '到场响应周期（H）',formType: 'number',value: '',defaultValue: 36 ,isNull: 1},
                ],
                // 一般条款
                other: [
                    { fieldName: 'numberContracts', name: '合同份数',formType: 'number',value: '',defaultValue: 2,isNull: 1,type: 'other'},
                    { fieldName: 'numberCopies', name: '各执份数',formType: 'text',value: '',defaultValue: 1,isNull: 1,type: 'other'},
                ]
            },
            
            // 承载表单数据
            formData: {},

            finalMoney: 0,
            rate: null,
            paymentConditionOptions:[
                {value: '合同签订后'},
                {value: '现场实施后'},
                {value: '项目验收后'}
            ],
            checkList: {
                paymentIsAll: false,
                invoiceIsAll: false
            }
        }
    },
    
    computed: {
        paymentOptions(){
            return this.paymentList.map(item => {
                let data = {
                    name:  item.payName,
                    value: item.payName
                }
                return data
            })
        },
        invoiceCycleOption(){
            return toolOptions.invoiceCycleOption
        }
    },

    watch: {
        value: {
            handler(val){
                this.paymentList = val.paymentList;
                this.invoiceList = val.invoiceList;
                this.annexList = val.annexList;
                this.finalMoney = val.entity && val.entity.money ? val.entity.money : 0;
                this.rate = val.entity && val.entity.rate ? val.entity.rate : 13;
            },
            deep: true,
            immediate: true
        },
        paymentList: {
            handler(val){
                if(val.length){
                    let allMoney = 0;
                    for(let i=0;i< val.length;i++){
                        allMoney = numberAdd(Number(allMoney),Number(val[i].paymentAmount) ? Number(val[i].paymentAmount) : 0)
                        val[i].is_error = true;
                        if(Number(val[i].paymentCycle) && val[i].paymentCondition.trim() && Number(val[i].paymentAmount) && Number(val[i].paymentPercentage)){
                            val[i].is_error = false;
                        }
                    }
                    if(allMoney >= Number(this.finalMoney)){
                        this.checkList.paymentIsAll = true;
                    }else{
                        this.checkList.paymentIsAll = false;
                    }
                }else{
                    this.checkList.paymentIsAll = false;
                }
                this.valueChange();
            },
            deep: true,
            immediate: true
        },
        invoiceList: {
            handler(val){
                if(val.length){
                    let allMoney = 0;
                    for(let i=0;i< val.length;i++){
                        allMoney = numberAdd(Number(allMoney),Number(val[i].invoiceAmount) ? Number(val[i].invoiceAmount) : 0)
                        val[i].is_error = true;
                        if(val[i].paymentNodeNumber && val[i].invoiceCycle && Number(val[i].invoiceAmount) && Number(val[i].invoicePercentage)){
                            val[i].is_error = false;
                        }
                    }
                    if(allMoney >= Number(this.finalMoney)){
                        this.checkList.invoiceIsAll = true;
                    }else{
                        this.checkList.invoiceIsAll = false;
                    }
                }else{
                    this.checkList.invoiceIsAll = false;
                }
                this.valueChange();
            },
            
            deep: true,
            immediate: true
        },
        annexList: {
            handler(val){
                 if(val.length){
                    for(let i=0;i< val.length;i++){
                        val[i].is_error = true;
                        if(val[i].annexName.trim() && val[i].files.length){
                            val[i].is_error = false;
                        }
                    }
                }
                this.valueChange();
            },
            deep: true,
            immediate: true
        }
    },

    mounted() {
        this.$nextTick(() => {
            this.handleFiledData();
        })
    },

    methods: {
        //字段数据处理
        handleFiledData(){
            Object.keys(this.fieldList).forEach(item => {
                this.formData[item] = [];
                this.fieldList[item].forEach(element => {
                    let param = {};
                    let tempList = [];
                    if(element.isNull == 1){
                        tempList.push({
                            required: true,
                            message: element.name + '不能为空',
                            trigger: ['change','blur']
                        })
                    }
                    if(element.formType == 'number'){
                        var validateCRMNumber = (rule, value, callback) => {
                            // debugger
                            if (!value || value == '' || !isNaN(value)) {
                                callback()
                            } else {
                                callback(new Error(element.name + '必须为数字'))
                            }
                        }
                        tempList.push({
                            validator: validateCRMNumber,
                            item: element,
                            trigger: ['change','blur']
                        })
                    }
                    this.formRules[element.fieldName] = tempList
                    
                    param['key'] = element.fieldName;
                    param['data'] = element;
                    param['value'] = element.value ? element.value : element.defaultValue;                    
                    this.formData[item].push(param);
                });
            })
            this.isShow = true;
        },
        
        // 编辑时，默认数据处理
        handleUpdateData(){
            Object.keys(this.formData).forEach(item => {
                this.formData[item].forEach(element => {
                    if(this.action.type == 'update'){
                        // debugger
                        let value = this.value.contractInfo[element.key];
                        element.value = value ? value : "";
                    }
                })
            })
        },

        // 合同表单数据更改
        formValueChange(data){
            let item = this.formData[data.formModular][data.index]
            item.value = data.value;
            this.contractInfo = {
                customerId: this.value.contractInfo.customerId,
                quotationId: this.value.contractInfo.quotationId,
                contractInfoId: this.value.contractInfo.contractInfoId
            };
            this.partInvoice = {
                customerId: this.value.contractInfo.customerId,
                contractPartInvoiceId: this.value.partInvoice.contractPartInvoiceId
            };
            Object.keys(this.formData).forEach(item => {
                if(item == 'invoice'){
                    this.formData[item].forEach(element => {
                        this.partInvoice[element.key] = element.value;
                    })
                }else{
                    this.formData[item].forEach(element => {
                        this.contractInfo[element.key] = element.value;
                    })
                }
            })
            this.valueChange();
        },

        //添加付款节点
        addPaymentItem(){
            let payment = {
                "paymentCycle": 5, // 付款周期
                "paymentPercentage": 0, // 付款百分比
                'payName': '',
                "paymentId": 0, // id
                "paymentAmount": 0, // 付款金额
                "paymentNodeNumber": this.paymentList.length+1, // 节点序号
                "paymentCondition": '', // 付款条件  1 合同签订后 2 现场实施后 3 项目验收后
            }
            if(this.paymentList.length == 5){
                this.$message.error('不能超过5个付款节点！');
                return
            }
            if(this.paymentList.length){
                let money = 0;
                let percentage = 0;
                for(let i=0;i<this.paymentList.length;i++){
                    if(this.paymentList[i].is_error){
                        this.$message.error('请先将付款节点'+ this.paymentList[i].paymentNodeNumber +'的数据补充完整，再添加！');
                        return;
                    }
                    
                    if(i == 0){
                        this.paymentList[i].payName = '首付款';
                    }
                    if(i > 0){
                        this.paymentList[i].payName = '第' + (i+1) + '笔';
                    }

                    money = numberAdd(money,Number(this.paymentList[i].paymentAmount)); 
                    percentage = numberAdd(percentage,Number(this.paymentList[i].paymentPercentage)); 
                }

                payment.payName = '尾款';
                payment.paymentAmount = numberSub(Number(this.finalMoney),money);
                payment.paymentPercentage = numberSub(100,percentage);
            }else{
                payment.payName = '全款';
                payment.paymentCondition = this.paymentConditionOptions[0].value;
                payment.paymentAmount = Number(this.finalMoney);
                payment.paymentPercentage = 100;
            }
            this.paymentList.push(payment)
        },

        // 付款周期，改变时，触发方法
        changePaymentCycle(index){
            let payment = this.paymentList[index];
            if(Number(payment.paymentCycle) < 0){
                this.$message.error('付款周期不能低于0，默认置为1！');
                payment.paymentCycle = 1;
            }
        },

        // 付款节点，金额改变时，触发的方法
        changePaymentAmount(index){
            let payment = this.paymentList[index];
            if(Number(payment.paymentAmount) < 0){
                this.$message.error('百分比不能低于0，默认置为0！');
                payment.paymentAmount = 0;
            }
            let money = 0;
            let percentage = 0;
            for(let i=0;i<this.paymentList.length;i++){
                money = numberAdd(money,Number(this.paymentList[i].paymentAmount)); 
                percentage = numberAdd(percentage,Number(this.paymentList[i].paymentPercentage)); 
            }
            if(money > Number(this.finalMoney)){
                this.$message.error('超过总金额了，默认填充为剩余金额！');
                payment.paymentAmount = numberSub(Number(this.finalMoney),numberSub(money,payment.paymentAmount)); 
                payment.paymentPercentage = numberSub(100,numberSub(percentage,payment.paymentPercentage)); 
            }else if(money == Number(this.finalMoney)){
                payment.paymentPercentage = numberSub(100,numberSub(percentage,payment.paymentPercentage)); 
            }else{
                payment.paymentPercentage =  numberSaveFloat(numberMul(100,numberDiv(payment.paymentAmount,this.finalMoney)),2,2)
            }
        },

        // 付款节点，百分比改变时，触发的方法
        changePaymentPercentage(index){
            let payment = this.paymentList[index];
            if(payment.paymentPercentage < 0){
                this.$message.error('百分比不能低于0，默认置为0！');
                payment.paymentPercentage = 0;
            }
            let money = 0;
            let percentage = 0;
            for(let i=0;i<this.paymentList.length;i++){
                money = numberAdd(money,Number(this.paymentList[i].paymentAmount)); 
                percentage = numberAdd(percentage,Number(this.paymentList[i].paymentPercentage)); 
            }
            if(percentage > 100){
                this.$message.error('百分比超过100，默认填充剩余百分比！');
                payment.paymentAmount = numberSub(Number(this.finalMoney),numberSub(money,payment.paymentAmount)); 
                payment.paymentPercentage = numberSub(100,numberSub(percentage,payment.paymentPercentage)); 
            }else if(percentage == 100){
                payment.paymentAmount = numberSub(Number(this.finalMoney),numberSub(money,payment.paymentAmount)); 
            } else {
                payment.paymentAmount =  numberSaveFloat((numberDiv(numberMul(payment.paymentPercentage,this.finalMoney),100)),2,2)
            }
        },

        // 删除付款节点
        paymentRemoveItem(index){
            this.paymentList.splice(index, 1);
            if(this.paymentList.length == 1){
                this.paymentList[0].payName = '全款'
            }else{
                this.paymentList.forEach((item,index) => {
                    if(index == 0){
                        item.payName = '首付款';
                    }else if(index > 0 && index != (this.paymentList.length - 1)){
                        item.payName = '第' + (index+1) + '笔';
                    }else{
                        item.payName = '尾款';
                    }
                    item.paymentNodeNumber = index + 1;
                })
            }
            // this.paymentList.forEach((item,index) => {
            //     item.paymentNodeNumber = index + 1;
            // })
            this.invoiceList.forEach(item => {
                item.paymentNodeNumber = null;
            })
        },

        //添加开票节点
        addTnvoiceItem(){
            let invoice = {
                "invoiceNodeNumber": this.invoiceList.length+1, // 开票节点 
                "invoicePercentage": Number(this.rate), // 开票税率
                "paymentNodeNumber": null, // 收款节点
                "invoiceId": 0, // 开票 id
                "invoiceCycle": 'same_month', // 开票周期
                "invoiceAmount": 0, // 开票金额
            }
            if(this.invoiceList.length == 5){
                this.$message.error('不能超过5个开票节点！');
                return
            }
            let money = 0;
            for(let i=0;i<this.invoiceList.length;i++){
                if(this.invoiceList[i].is_error){
                    this.$message.error('请先将开票节点'+ this.invoiceList[i].invoiceNodeNumber +'的数据补充完整，再添加！');
                    return;
                }
                money = numberAdd(money,Number(this.invoiceList[i].invoiceAmount)); 
            }
            invoice.invoiceAmount = numberSub(Number(this.finalMoney),money);
            this.invoiceList.push(invoice)
        },

        // 开票节点，金额改变时，触发的方法
        changeInvoiceAmount(index){
            let invoice = this.invoiceList[index];
            if(Number(invoice.invoiceAmount) < 0){
                this.$message.error('百分比不能低于0，默认置为0！');
                invoice.invoiceAmount = 0;
            }
            let money = 0;
            for(let i=0;i<this.invoiceList.length;i++){
                money = numberAdd(money,Number(this.invoiceList[i].invoiceAmount)); 
            }
            if(money > Number(this.finalMoney)){
                this.$message.error('超过总金额了，默认填充为剩余金额！');
                invoice.invoiceAmount = numberSub(Number(this.finalMoney),numberSub(money,invoice.invoiceAmount)); 
            }
        },

        // 删除开票节点
        invoiceRemoveItem(index){
            this.invoiceList.splice(index, 1)
            this.invoiceList.forEach((item,index) => {
                item.invoiceNodeNumber = index + 1;
            })
        },

        
        // 文件上传
        fileDataChange(data){
            let file = this.annexList[data.index];
            file.batchId = data.batchId;

            if(data.value && data.value.length && !file.annexName.length){
                let fileName = data.value[0].name;
                file.annexName = fileName.substring(0, fileName.lastIndexOf("."));
            }

            file.files = data.value;
        },
        
        // 新增附件记录
        addFiles(){
            let file = {
                "annexId": 0,
                "batchId": "",// 文件批次 id
                "files": [],
                "annexName": "" // 附件名称
            }
            this.annexList.push(file)
        },
        
        // 删除附件记录
        removeFile(index){
            this.annexList.splice(index, 1)
        },

        save(){
            let isAllValid = false;
            //验证表单是否都填写完成
            let formValid = true;
            Object.keys(this.fieldList).forEach(item => {
                this.$refs['contractForm_'+item].$refs['fieldForm_'+item].validate(valid => {
                    if(!valid){
                        formValid = false;
                    }
                })
            })
            if(!formValid){
                this.$message.error('请完善表单信息！');
                return false
            }
            // 付款节点
            let paymentValid = true;
            let paymentList = this.paymentList;
            if(!this.checkList.paymentIsAll){ //付款节点金额与总金额不匹配
                this.$message.error('付款节点金额与总金额不匹配！');
                return false
            }else{
                for(let i=0;i< paymentList.length;i++){
                    if(paymentList[i].is_error){
                        this.$message.error('请完善付款节点信息！');
                        return false;
                    }
                }
            }
            
            // 开票节点
            let invoiceValid = true;
            let invoiceList = this.invoiceList;
            if(!this.checkList.invoiceIsAll){ //付款节点金额与总金额不匹配
                this.$message.error('开票节点金额与总金额不匹配！');
                return false
            }else{
                for(let i=0;i< invoiceList.length;i++){
                    if(invoiceList[i].is_error){
                        this.$message.error('请完善开票节点信息！');
                        return false;
                    }
                }
            }

            // 合同附件
            let annexList = this.annexList;
            if(annexList.length){
                for(let i=0;i< annexList.length;i++){
                    if(annexList[i].is_error){
                        this.$message.error('请完善附件信息！');
                        return false;
                    }
                }
            }
            // if(!annexList.length){
            //     this.$message.error('请添加附件！');
            // }else{
            //     for(let i=0;i< annexList.length;i++){
            //         if(annexList[i].is_error){
            //             this.$message.error('请完善附件信息！');
            //             return false;
            //         }
            //     }
            // }

            return true;

        },

        tableRowClassName({row, rowIndex}) {
            // console.log(row)
            if(row.is_error){
                return 'error-row'              
            }
            return '';
        },

        // 数据更改，并处理
        valueChange(){
            let param = {
                partInvoice: objDeepCopy(this.partInvoice), // 开票信息
                contractInfo: objDeepCopy(this.contractInfo), // 合同其他相关信息，包含甲方信息，乙方信息，产品交付与验收，质量保证、保修及服务期限
                invoiceList: this.invoiceList, // 开票节点及金额
                paymentList: this.paymentList, //付款节点及金额
                annexList: this.annexList, //合同附件
            }
            this.$emit('value-change',param);
        },
        
        // 付款条件选项过滤
        querySearch(queryString, cb) {
            var restaurants = this.paymentConditionOptions;
            var results = queryString ? restaurants.filter(item => {return item.value.indexOf(queryString) != -1}) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },

        // 付款节点条件过滤
        querySearchPayList(queryString, cb){
            var restaurants = this.paymentOptions;
            var results = queryString ? restaurants.filter(item => {return item.value.indexOf(queryString) != -1}) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        }
        
    }
    
}
</script>

<style lang="scss">
.input-popper{
    min-width: 120px;
}

.el-table .error-row {
    background: rgba(245,108,108, 0.5)
}
</style>